/**
 * zmn 花名册模块-员工档案
 * @author tanghongjun
 * @since 2020-05-14 10:56:45
 */
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate', 'upload'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var layedit = layui.layedit;
    let laydate = layui.laydate;
    let upload = layui.upload;
    let timestamp = new Date().getTime();

    if (json.staffArchives.idcardImgSrc != null) {
        reLoadImage("idcardImgSrc", json.staffArchives.idcardImgSrc, "idcardImgSrcValue");
    }

    if (json.staffArchives.idcardImgSrc2 != null) {
        reLoadImage("idcardImgSrc2", json.staffArchives.idcardImgSrc2, "idcardImgSrcValue2");
    }

    if (json.staffArchives.idcardImgSrc3 != null) {
        reLoadImage("idcardImgSrc3", json.staffArchives.idcardImgSrc3, "idcardImgSrcValue3");
    }

    //初始化文件上传插件
    uploaderImage("idcardImgSrc", "idcardImgSrcValue");
    uploaderImage("idcardImgSrc2", "idcardImgSrcValue2");
    uploaderImage("idcardImgSrc3", "idcardImgSrcValue3");

    if (json.staffArchives.idCardValidityTime != null) {
        laydate.render({
            elem: "#idCardValidityTime",
            type: "date",
            value: new Date(json.staffArchives.idCardValidityTime)
        });
    } else {
        laydate.render({elem: "#idCardValidityTime", type: "date"});
    }

    if (json.staffArchives.birthday != null) {
        laydate.render({elem: "#birthday", type: "date", value: new Date(json.staffArchives.birthday)});
    } else {
        laydate.render({elem: "#birthday", type: "date"});
    }

    if (json.staffArchives.socialSecurityStartTime != null) {
        laydate.render({
            elem: "#socialSecurityStartTime",
            type: "date",
            value: new Date(json.staffArchives.socialSecurityStartTime)
        });
    } else {
        laydate.render({elem: "#socialSecurityStartTime", type: "date"});
    }

    if (json.staffArchives.socialSecurityStopTime != null) {
        laydate.render({
            elem: "#socialSecurityStopTime",
            type: "date",
            value: new Date(json.staffArchives.socialSecurityStopTime)
        });
    } else {
        laydate.render({elem: "#socialSecurityStopTime", type: "date"});
    }

    if (json.staffArchives.graduationTime != null) {
        laydate.render({elem: "#graduationTime", type: "date", value: new Date(json.staffArchives.graduationTime)});
    } else {
        laydate.render({elem: "#graduationTime", type: "date"});
    }

    if (json.staffArchives.joinWorkingTime != null) {
        laydate.render({elem: "#joinWorkingTime", type: "date", value: new Date(json.staffArchives.joinWorkingTime)});
    } else {
        laydate.render({elem: "#joinWorkingTime", type: "date"});
    }

    // 区域下拉框联动
    zmnPage.laySelectLinkage(form, "/common/area/listChilds.action", "provinceId", "cityId", "countryId");
    form.render(null, "zmn-form");

    //  获取上一次上传图片的时间戳
    function getImageTimestamp(url) {
        var index = url.lastIndexOf("/");
        var str = url.substring(0, index);
        index = str.lastIndexOf("/");
        str = str.substring(index + 1, str.length);
        return str;
    }

    $("#idCardNumber").blur(function(){
        var curValue=$("#idCardNumber").val();

        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if(reg.test(curValue))
        {
            let age = calcAge(curValue);
            $("#age").val(age);
        } else {
            $("#age").val("");
        }
    });

    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        var data = obj.field;
        var url = "/staff/staffarchives/addEdit.action";

        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (result) {
                if (result.status == 200) {
                    //提示信息为弹出框形式
                    parent.layer.open({
                        title: "温馨提示",
                        content: json.message.replace("【", "【<span style='color:red;'>").replace("】", "</span>】")
                    });
                } else {
                    layer.msg(result.message, {"icon": 2});
                }


            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        })
        return false;
    });

    /**
     * 描述: 图片上传方法
     * @param elemId
     * @param valueId
     */
    let indexUploadImags;

    function uploaderImage(elemId, valueId) {
        upload.render({
            elem: '#' + elemId
            , exts: 'jpg|png|jpeg'
            , acceptMime: 'image/*'
            , accept: 'images'
            , url: '/staff/staffarchives/uploaderImage.action?timestamp=' + timestamp + '&elemId=' + elemId
            , size: 3072
            , before: function (obj) {
                indexUploadImags = layui.layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            }
            , done: function (res) {
                if (res.code == 2) {
                    var data = res.data;
                    $("#" + valueId).val(data.src);
                    $("#" + elemId).attr("style", "background:url( " + data.src + "?" + Date.now() + ");background-size:100% 100%;background-repeat:no-repeat;");
                    let next = $("#" + valueId).next();
                    let next1 = $(next).next();
                    $(next).attr("style", "visibility:hidden !important");
                    $(next1).attr("style", "visibility:hidden !important");
                } else {
                    layer.msg("上传失败！")
                }
                layui.layer.close(indexUploadImags);
            }
        });
    }


    function reLoadImage(elemId, value, valueId) {
        zmnUploadUtil.reLoadImage($, elemId, value, valueId);
    }

    //对外暴露的接口
    exports('plat_staffarchives_detail', {});
});

function previewImg(element) {
    //调整预览大小
    var img = new Image();
    img.src = document.getElementById(element).value;
    // img.src = obj.src;
    var imgHtml = "<img src='" + img.src + "' width='100%' height='100%'/>";
    //弹出层
    layer.open({
        type: 1,
        shade: 0.8,
        offset: 'auto',
        area: [600 + 'px', 300 + 'px'],
        shadeClose: true,
        scrollbar: false,
        title: "", //不显示标题
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        cancel: function () {
            //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
        }
    });
}

function deleteImg(element) {
    var elementValue = element + 'Value';
    document.getElementById(element).removeAttribute('style');
    Array.from(document.getElementById(element).children).forEach(function (item) {
        item.removeAttribute('style');
    });
    document.getElementById(elementValue).removeAttribute('value');
}

/**根据身份证计算年龄
 *@param idCard 身份证号码
 */
function calcAge(idCard) {
    //获取年龄
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - idCard.substring(6, 10) - 1;
    if (idCard.substring(10, 12) < month || idCard.substring(10, 12) == month && idCard.substring(12, 14) <= day) {
        age++;
    }

    return age;
}